﻿using System;
using System.Web.UI;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace Guru.Web.Controls.Validators
{
    public class RegExValidationItem : ValidationItem
    {
        #region const   
        /// <summary>
        /// The custom message to display
        ///     {0}: The message
        /// </summary>
        protected const string _JS_MESSAGE = "regex: \"{0}\"";

        /// <summary>
        ///  Add rule
        ///     {0}: ClientId of yhe control
        ///     {1}: RegularExpression
        ///     {2}: The message
        /// </summary>
        protected const string _JS_RULE = @"
            if($('#{0}') != null)
                $('#{0}').rules('add', [OPEN]
                    regex: '{1}',
                     messages: [OPEN]
                        {2}
                    [CLOSE]
                [CLOSE]); 
                ";
        #endregion

        /// <summary>
        /// RegularExpression
        /// </summary>
        [Category("Behavior"), DefaultValue(""),
        Description("RegularExpression"), NotifyParentProperty(true)]
        public string RegularExpression
        {
            set
            {               
                ViewState["RegularExpression"] = value;
            }
            get
            {
                if (ViewState["RegularExpression"] == null) throw new PropertyNullRefException("RegularExpression");
                return (string)ViewState["RegularExpression"];
            }
        }

        #region Redering
        public override string RenderTrigger(HtmlTextWriter writer)
        {
            return string.Empty;
        }

        public override string RenderRuleRegister(HtmlTextWriter writer)
        {           
            string message = string.Empty;
            if (string.IsNullOrEmpty(this.Message) == false)
                message = string.Format(_JS_MESSAGE, this.Message);
            string basicRule = string.Format(_JS_RULE, this.ObjectControlToValidate.ToJQueryId(),this.RegularExpression, message);
            return basicRule.ReplaceTag();
        }
       
        #endregion
    }
}
